package com.zyh.servlet;

import com.alibaba.fastjson2.JSONObject;
import com.zyh.domain.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;


@WebServlet("/req")
public class RequestTestServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //  ******************* 获取请求行 *******************
        System.out.println("******************* 获取请求行 *******************");
        // 获取请求参数
        System.out.println(req.getMethod());
        // 获取项目的虚拟路径，项目的前缀
        System.out.println(req.getContextPath());
        // 获取完整的请求地址
        System.out.println(req.getRequestURL());
        // 获取资源地址，去掉协议、ip和端口号之后的地址
        System.out.println(req.getRequestURI());
        // 获取到所有的地址参数
        System.out.println(req.getQueryString());

        //  ******************* 获取请求头 *******************
        System.out.println("******************* 获取请求头 *******************");
        System.out.println("Accept: " + req.getHeader("Accept"));
        System.out.println("host: " + req.getHeader("host"));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //  ******************* 获取请求体 *******************
        System.out.println("******************* 请求体获取 *******************");
        // 通过输入流进行获取
        // 字节输入流
        // InputStream is = req.getInputStream();
        // 字符缓冲流
        // 解决中文乱码问题
        req.setCharacterEncoding("utf-8");
        BufferedReader br = req.getReader();
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        JSONObject object = JSONObject.parseObject(sb.toString());
        System.out.println(object);
        // 转成java bean
        Student student = JSONObject.parseObject(sb.toString(), Student.class);
        System.out.println(student.getName());
    }
}
